/* mf1a.p - Mfg/pro Manufacturing Entry Program - Translatable Section        */
/* Copyright 1986 QAD Inc. All rights reserved.                               */
/* $Id:: mf1a.p 80230 2017-07-19 22:28:09Z ejt                             $: */
/*                                                                            */
/*                                                                            */
/*                                                                            */
/* Note: All translatable source code for the startup procedures should       */
/*       be placed into this routine.  This program should be placed          */
/*       in the same directory as mfmenu.p, not mf.p and mf1.p.               */
/*       05/14/93 - rwl                                                       */
/*                                                                            */
/*                                                                     *H259* */
/*                                                                     *Hxxx* */
/*  Revision:       By: rwl            Date: 05/18/93  Rel: 7.3   ECO: *GA97* */
/*  Revision:       By: rwl            Date: 06/25/93  Rel: 7.3   ECO: *GC72* */
/*  Revision:       By: rwl            Date: 06/29/93  Rel: 7.3   ECO: *GC82* */
/*  Revision:       By: gjp            Date: 09/22/93  Rel: 7.3   ECO: *GF76* */
/*  Revision:       By: rwl            Date: 10/04/93  Rel: 7.3   ECO: *GG14* */
/*  Revision:       By: dgh            Date: 10/27/93  Rel: 7.4   ECO: *H213* */
/*  Revision:       By: rwl            Date: 11/15/93  Rel: 7.4   ECO: *H223* */
/*  Revision:       By: rwl            Date: 11/16/93  Rel: 7.4   ECO: *H231* */
/*  Revision:       By: rmh            Date: 06/09/94  Rel: 7.4   ECO: *FO45* */
/*  Revision:       By: rmh            Date: 06/14/94  Rel: 7.4   ECO: *FO83* */
/*  Revision:       By: rmh            Date: 08/23/94  Rel: 7.4   ECO: *H485* */
/*  Revision:       By: rmh            Date: 07/13/94  Rel: 7.4   ECO: *FO79* */
/*  Revision:       By: dgh            Date: 09/19/94  Rel: 7.4   ECO: *FR63* */
/*  Revision:       By: ame            Date: 11/02/94  Rel: 7.4   ECO: *GO04* */
/*  Revision:       By: ame            Date: 12/09/94  Rel: 7.4   ECO: *GO82* */
/*  Revision:       By: rwl            Date: 01/13/95  Rel: 7.4   ECO: *G0C0* */
/*  Revision:       By: jzs            Date: 03/25/95  Rel: 7.4   ECO: *G0KC* */
/*  Revision:       By: aed            Date: 04/10/95  Rel: 7.4   ECO: *H0D2* */
/*  Revision:       By: srk            Date: 04/27/95  Rel: 7.4   ECO: *H0DH* */
/*  Revision:       By: dzn            Date: 06/05/95  Rel: 7.4   ECO: *H0DS* */
/*  Revision:       By: jzs            Date: 10/27/95  Rel: 7.4   ECO: *H0GM* */
/*  Revision:       By: str            Date: 11/01/95  Rel: 7.4   ECO: *G1BN* */
/*  Revision:       By: dxb            Date: 12/01/95  Rel: 7.4   ECO: *F0WH* */
/*  Revision:       By: dzn            Date: 12/13/95  Rel: 7.4   ECO: *G1G9* */
/*  Revision:       By: jzs            Date: 12/20/95  Rel: 7.4   ECO: *G1GR* */
/*  Revision:       By: tvo            Date: 11/28/95  Rel: 7.4   ECO: *J094* */
/*  Revision:       By: aed            Date: 03/27/85  Rel: 7.4   ECO: *J0G1* */
/*  Revision:       By: jpm            Date: 04/03/96  Rel: 7.4   ECO: *G1MP* */
/*  Revision:       By: GWM            Date: 04/24/96  Rel: 7.4   ECO: *J0K8* */
/*  Revision:       By: taf            Date: 07/02/96  Rel: 7.4   ECO: *J0X5* */
/*  Revision:       By: taf            Date: 07/10/96  Rel: 7.4   ECO: *J0YK* */
/*  Revision:       By: rkc            Date: 07/12/96  Rel: 7.4   ECO: *G1WV* */
/*  Revision:       By: jpm            Date: 10/22/96  Rel: 7.4   ECO: *K017* */
/*  Revision:       By: dxb            Date: 11/11/96  Rel: 7.4   ECO: *H0P2* */
/*  Revision:       By: JPM            Date: 03/12/97  Rel: 8.6   ECO: *K081* */
/*  Revision:       By: Duane Burdett  Date: 03/26/97  Rel: 8.6   ECO: *G2LR* */
/*  Revision:       By: Cynthia J. Te  Date: 04/04/97  Rel: 8.6   ECO: *G2M3* */
/*  Revision:       By: David J. Seo   Date: 04/04/97  Rel: 8.6   ECO: *J1JH* */
/*  Revision:       By: David J. Seo   Date: 04/15/97  Rel: 8.6   ECO: *G2M9* */
/*  Revision:       By: Verghese Kuri  Date: 04/29/97  Rel: 8.6   ECO: *J1Q5* */
/*  Revision:       By: David J. Seo   Date: 05/27/97  Rel: 8.6   ECO: *G2N4* */
/*  Revision:       By: Cynthia Terry  Date: 07/07/97  Rel: 8.6   ECO: *J1VR* */
/*  Revision:       By: John Worden    Date: 07/18/97  Rel: 8.6   ECO: *K0GN* */
/*  Revision:       By: Jean Miller    Date: 09/12/97  Rel: 8.6   ECO: *K0HY* */
/*  Revision:       By: Patrick Rowan  Date: 09/12/97  Rel: 8.6   ECO: *J1YW* */
/*  Revision:       By: Surendra Kuma  Date: 10/03/97  Rel: 8.6   ECO: *K0JN* */
/*  Revision:       By: Steve Nugent   Date: 10/28/97  Rel: 8.6   ECO: *J24M* */
/*  Revision:       By: A. Rahane      Date: 02/23/98  Rel: 8.6E  ECO: *L007* */
/*  Revision:       By: A. Rahane      Date: 03/02/98  Rel: 8.6E  ECO: *L008* */
/*  Revision:       By: Suhas Bhargav  Date: 05/06/98  Rel: 8.6E  ECO: *J2JB* */
/*  Revision:       By: Alfred Tan     Date: 05/20/98  Rel: 8.6E  ECO: *K1Q4* */
/*  Revision:       By: Sachin Shah    Date: 05/26/98  Rel: 8.6E  ECO: *J2KK* */
/*  Revision:       By: Paul Knopf     Date: 06/02/98  Rel: 8.6E  ECO: *K1NM* */
/*  Revision:       By: Viswanathan M  Date: 06/19/98  Rel: 8.6E  ECO: *J2PL* */
/*  Revision:       By: Raphael Thopp  Date: 07/23/98  Rel: 8.6E  ECO: *J2TM* */
/*  Revision:       By: Vijaya Pakala  Date: 09/25/98  Rel: 8.6E  ECO: *J2Z2* */
/*  Revision:       By: Vijaya Pakala  Date: 11/10/98  Rel: 8.6E  ECO: *J33W* */
/*  Revision:       By: Mayse Lai      Date: 12/17/98  Rel: 9.0   ECO: *M03R* */
/*  Revision:       By: Vijaya Pakala  Date: 01/14/99  Rel: 9.0   ECO: *J38L* */
/*  Revision:       By: Hemanth Ebene  Date: 03/10/99  Rel: 9.0   ECO: *M0B8* */
/*  Revision:       By: Alfred Tan     Date: 03/13/99  Rel: 9.0   ECO: *M0BD* */
/*  Revision:       By: A. Philips     Date: 08/09/99  Rel: 9.0   ECO: *J3KC* */
/*  Revision:       By: Robin McCarth  Date: 09/28/99  Rel: 9.1   ECO: *N014* */
/*  Revision:       By: Jean Miller    Date: 11/24/99  Rel: 9.0   ECO: *M0G0* */
/*  Revision:       By: Kevin Schantz  Date: 12/05/99  Rel: 9.1   ECO: *J3MV* */
/*  Revision:       By: Raphael Thopp  Date: 12/15/99  Rel: 9.1   ECO: *J3N0* */
/*  Revision:       By: Jean Miller    Date: 03/06/00  Rel: 9.1   ECO: *N082* */
/*  Revision:       By: Raphael Thoppil Date: 02/23/00  Rel: 9.1  ECO: *J3PC* */
/*  Revision: 1.48  By: Dennis Taylor    Date: 03/27/00  Rel: 9.1 ECO: *N08T* */
/*  Revision: 1.50  By: Bill Gates       Date: 01/28/00  Rel: 9.1 ECO: *N06R* */
/*  Revision: 1.51  By: Annasaheb Rahane Date: 07/12/00  Rel: 9.1 ECO: *N0FX* */
/*  Revision: 1.52  By: Jean Miller      Date: 08/09/00  Rel: 9.1 ECO: *N0JS* */
/*  Revision: 1.53  By: Jean Miller      Date: 08/10/00  Rel: 9.1 ECO: *N0JY* */
/*  Revision: 1.54  By: Annasaheb Rahane Date: 09/25/00  Rel: 9.1 ECO: *N0S8* */
/*  Revision: 1.55  By: Jean Miller      Date: 10/23/00  Rel: 9.1 ECO: *N0T3* */
/*  Revision: 1.57    By: Jean Miller       Date: 07/30/01        ECO: *N10T* */
/*  Revision: 1.58    By: Falguni D.        Date: 08/06/01        ECO: *P01D* */
/*  Revision: 1.59    By: Anil Sudhakaran   Date: 10/18/01        ECO: *M1ND* */
/*  Revision: 1.60    By: Dipesh Bector     Date: 11/19/01        ECO: *N167* */
/*  Revision: 1.61    By: Raju Murugesan    Date: 06/13/02        ECO: *P07X* */
/*  Revision: 1.66    By: Jean Miller       Date: 06/20/02        ECO: *P09H* */
/*  Revision: 1.72    By: Mugdha Tambe      Date: 07/21/02        ECO: *P08G* */
/*  Revision: 1.74    By: Jean Miller       Date: 08/13/02        ECO: *P0F5* */
/*  Revision: 1.76    By: Jean Miller       Date: 08/15/02        ECO: *P0FG* */
/*  Revision: 1.77    By: Rajaneesh S.      Date: 08/29/02        ECO: *M1BY* */
/*  Revision: 1.78    By: Jean Miller       Date: 11/25/02        ECO: *P0KS* */
/*  Revision: 1.79    By: Rafal Krzyminski  Date: 01/15/03        ECO: *P0LX* */
/*  Revision: 1.81    By: Marek Krajanowski Date: 02/27/03        ECO: *P0NH* */
/*  Revision: 1.82    By: Narathip W.       Date: 04/30/03        ECO: *P0QX* */
/*  Revision: 1.85    By: Paul Donnelly     DATE: 07/01/03        ECO: *Q00H* */
/*  Revision: 1.86    By: Ed van de Gevel   DATE: 07/08/03        ECO: *Q003* */
/*  Revision: 1.87    By: Neil Curzon       DATE: 09/12/03        ECO: *Q039* */
/*  Revision: 1.88    By: Jean Miller       Date: 09/22/03        ECO: *P12V* */
/*  Revision: 1.92    By: Michael Hansen    Date: 11/14/03        ECO: *Q04K* */
/*  Revision: 1.93    By: Michael Hansen    Date: 04/06/04        ECO: *Q06Y* */
/*  Revision: 1.94    By: Narathip W.       Date: 06/08/04        ECO: *P256* */
/*  Revision: 1.95    BY: Michael Hansen    DATE: 07/15/04        ECO: *Q06H* */
/*  Revision: 1.96    BY: Vinay Soman       DATE: 08/19/04        ECO: *Q0CF* */
/*  Revision: 1.97    BY: Vinay Soman       DATE: 08/24/04        ECO: *P2GK* */
/*  Revision: 1.105   BY: Michael Hansen    DATE: 10/27/04        ECO: *Q0D7* */
/*  Revision: 1.113   BY: Michael Hansen    DATE: 11/08/04        ECO: *Q0F7* */
/*  Revision: 1.116   BY: Sandy Brown       DATE: 01/04/05        ECO: *P2HX* */
/*  Revision: 1.118   BY: Tiziana Giustozzi DATE: 05/02/05        ECO: *Q0HZ* */
/*  Revision: 1.120   BY: Abhishek Jha      DATE: 08/25/05        ECO: *P3ZJ* */
/*  Revision: 1.121   BY: Sushant Pradhan   DATE: 09/26/05        ECO: *P42J* */
/*  Revision: 1.124   BY: Shilpa Kamath     DATE: 11/03/05        ECO: *R02B* */
/*  Revision: 1.125   BY: Amit Singh        DATE: 12/13/05        ECO: *P4C0* */
/*  Revision: 1.126   BY: Austin Xie        DATE: 06/05/06        ECO: *R05Y* */
/*  Revision: 1.127   BY: Fred Yeadon       DATE: 06/08/06        ECO: *Q0LK* */
/*  Revision: 1.131   BY: Edgar Roca        DATE: 06/15/06        ECO: *R03Q* */
/*  Revision: 1.132   BY: Austin Xie        DATE: 06/06/06        ECO: *R06V* */
/*  Revision: 1.135   BY: Katie Hilbert     DATE: 08/15/07        ECO: *Q16K* */
/*  Revision: 1.136   BY: Jean Miller       DATE: 08/16/07        ECO: *R0C6* */
/*  Revision: 1.137   BY: Austin Xie        DATE: 01/16/08        ECO: *R090* */
/*  Revision: 1.138   BY: Katie Hilbert     DATE: 01/18/08        ECO: *Q1GM* */
/*  Revision: 1.139   BY: Michael Yan       DATE: 01/30/08        ECO: *R0MB* */
/*  Revision: 1.140   BY: Dilip Manawat     DATE: 02/01/08        ECO: *R0LW* */
/*  Revision: 1.141   BY: Jean Miller       DATE: 01/23/08        ECO: *R0LN* */
/*  Revision: 1.142   BY: Ashim Mishra      DATE: 03/24/08        ECO: *Q1DJ* */
/*  Revision: 1.144   BY: Rijoy Ravindran   DATE: 10/03/08        ECO: *Q1TX* */
/*  Revision: 1.145   BY: Justin Zhang      DATE: 07/08/10        ECO: *R21R*  */
/*-Revision end---------------------------------------------------------------*/

/******************************************************************************/
/* All patch markers and commented out code have been removed from the source */
/* code below. For all future modifications to this file, any code which is   */
/* no longer required should be deleted and no in-line patch markers should   */
/* be added.  The ECO marker should only be included in the Revision History. */
/******************************************************************************/

routine-level on error undo, throw.

using com.qad.eefin.buser.EntitySecurityCheck.
using com.qad.qra.config.QraConfig.

{us/bbi/pxgblmgr.i &NOSHARED}
{us/bbi/mfdeclre.i}

{us/bbi/mf1.i}
{us/px/pxsevcon.i}

{us/px/pxmaint.i}
{us/mg/mgconsdf.i}
{us/lv/lvapidef.i}

/* TempTable Definition for User Domains and Companies */
{proxy/session/getdomainsandcompaniesforuserdef.i}

/*************************** Local Variabls *************************/
define variable lMultiDomains as logical initial false.
define variable lF4NotPressed as logical initial true.
define variable lChuilogout-response as character no-undo.

/************************** Function Prototypes *********************/
function offerNewPassword returns character
   (input p-userid as character) forward.

&SCOPED-DEFINE CONCURRENT-SESSIONS 0
&SCOPED-DEFINE NAMED-USERS         1
&SCOPED-DEFINE LOCATION-USERS      2
&SCOPED-DEFINE CAPACITY-UNITS      3
&SCOPED-DEFINE FIXED-PRICE         4

/* MAKE LABEL FUNCTION DECLARATIONS AND RUN LABEL PROGRAM PERSISTENT. */
/* IN CHUI THE PERSISTENT GPLABEL.P IS RESTARTED IF WE'VE RETURNED    */
/* HERE FROM THE MENU SYSTEM. IN EFFECT EMPTYING THE LABEL TEMP TABLE */
/* ALLOWING NEW LABELS ADDED DURING THE SESSION TO BE USED.           */
{us/bbi/gplabel.i &ClearReg=yes}

{us/bbi/gpfilev.i}

define shared variable h_mfinitpl as handle no-undo.
define shared variable password_required as logical initial yes no-undo.

define variable i as integer no-undo.
define variable token1 as character no-undo.
define variable current_user_lang like global_user_lang no-undo.

define variable passwd as character label "Password" format "x(16)"
   case-sensitive no-undo.

define variable temp_vers as character no-undo format "x(78)".
define variable o_passwd like passwd no-undo.

define variable expdays like usrc_expire_days no-undo.
define variable expired like mfc_logical initial no no-undo.

define variable first-time      as logical initial true     no-undo.
define variable v_cur           as integer    no-undo.
define variable v_max           as integer    no-undo.
define variable v_secure        as logical    no-undo.
define variable v_sid           as character  no-undo.
define variable lv-handle       as handle     no-undo.
define variable v_licType       as integer    no-undo.
define variable v_licDesc       as character  no-undo.

define variable c-welcome           as character format "x(78)" no-undo.
define variable c-allrightsreserved as character format "x(27)" no-undo.
define variable c-notreproduced     as character format "x(78)" no-undo.
define variable h-widget            as handle no-undo.
define variable msg-text        like msg_desc no-undo.
define variable l_usercount     as integer no-undo.
define variable l_locked        as logical no-undo.
define variable using_GRS      like mfc_logical no-undo label "Using GRS".

define variable new_list        as character no-undo.
define variable userISOCountry  as character no-undo.
define variable c-countryCode   as character no-undo.
define variable c-variantCode   as character no-undo.

define variable lv_domain like dom_domain no-undo.
define variable l_error   as integer      no-undo.

define variable i-msg-number      as integer   no-undo.
define variable c-msg-desc        as character no-undo.
define variable c-status          as character no-undo.
define variable c-userid          as character no-undo.
define variable c-password        as character no-undo
                label "Password" format "x(16)" case-sensitive.
define variable c-last-log-date  as character no-undo.
define variable c-last-log-time  as character no-undo.
define variable c-last-log-zone  as character no-undo.
define variable c-access-token   as character no-undo.

define variable c-logon          as integer   no-undo.
define variable c-ret-message    as character no-undo.
define variable l-ret-value      as logical   no-undo.
define variable l_authorized     as logical   no-undo.
define variable l_enforce_os_userid as logical initial no no-undo.
define variable opErrorMsg       as integer   no-undo.

define variable l_suddenExit     as logical   no-undo.

/* For calling QAD Financials Data Object to check GL Entity Security */
define variable hQADFinancialsLib as   handle      no-undo.
define variable EntitySecurity    as EntitySecurityCheck no-undo.
define variable valid_entity      like mfc_logical no-undo.

define variable authService as class com.qad.qra.security.IAuthenticationService.
define variable rawPassword as raw no-undo.
define variable p-application as character no-undo.

define buffer qadwkfl for qad_wkfl.

/* SET MESSAGE HANDLER TO RUN PROCEDURE REGISTERREASONMESSAGE */
run setMessageHandlerHandle in h_mfinitpl
   (input this-procedure).

subscribe to "previousSuccessfulLogin" in h_mfinitpl.

if QraConfig:IsEnabled
then do:
   authService = cast(com.qad.qra.core.GlobalServiceLocator:Current:GetInstance(
                         Progress.Lang.Class:GetClass("com.qad.qra.security.IAuthenticationService")),
                         com.qad.qra.security.IAuthenticationService).
end.

/* Start pxtools.p for exception handling */
getGlobalHandle (input "GeneralPurposeTools").

/* PERSISTENT PROCEDURE SETS MODE TO MAINT OR VIEW */
define variable hViewer as handle     no-undo.
{us/bbi/gprun.i ""gpvwxr.p"" "persistent set hViewer"}
hViewer:PRIVATE-DATA = "gpvwxr".

{us/gp/gprunpdf.i "gpurxr" "p"}
{us/gp/gprunpdf.i "lvgenpl" "p"}

define variable passwd-matched  like mfc_logical no-undo.

/* SET EXTERNALIZED LABELS FOR VARIABLES USED AS LABELS. */
c-welcome = getTermLabelCentered("MFG/PRO_WELCOME",78).
c-allrightsreserved = getTermLabel("ALL_RIGHTS_RESERVED",27) + ".".

/* GET REPRODUCED MESSAGE FROM MESSAGE MASTER WHEN AVAILABLE. */
{us/bbi/pxmsg.i &MSGNUM=3775 &ERRORLEVEL=1 &MSGBUFFER=c-notreproduced}

/* CENTER LABEL */
run centerLabel in h-label
   (input 78,
   input-output c-notreproduced).

/*WELCOME AND PRODUCT LICENSE AUDIT FRAME*/
form
   skip(1)
   c-welcome no-label
   temp_vers no-label skip
   "QAD" at 38
   "100 Innovation Place" at 30
   "Santa Barbara, CA  93108" at 28
   skip(1)
   "(805) 684-6614" at 32
   "(805) 565-4202 FAX" at 32
   skip(1)
   "Copyright 1986 QAD Inc." at 18
   c-allrightsreserved no-label skip
   c-notreproduced no-label skip
   v_cur format ">>>9" colon 29
   v_max format ">>>9" colon 60 skip(1)
   c-userid      colon 40 label "User ID" format "x(8)"
   c-password    colon 40
   lv_domain           colon 40 dom_name no-label
with frame welcome side-labels width 80.

/* SET EXTERNALIZED LABELS FRAME WELCOME. */
v_cur:label         = getTermLabel("ACTIVE_SESSIONS",20).
v_max:label         = getTermLabel("SESSIONS_ALLOWED",26).
lv_domain:label     = getTermLabel("DOMAIN",35).
c-userid:label      = getTermLabel("User_ID",39).
c-password:label    = getTermLabel("PASSWORD",39).

/*NEW PASSWORD FRAME*/
form
   skip(1)
   skip(1)
   passwd colon 20 label "New Password"
   skip(1)
   skip(1)
with frame b side-labels overlay width 70 centered row 12.

/* SET EXTERNALIZED LABELS FRAME B. */
passwd:label in frame b = getTermLabel("NEW_PASSWORD",18).

/*SEARCH FOR VERSION INFORMATION*/
/* Call gpgetver.p to get Version Information */
{us/bbi/gprun.i ""gpgetver.p""
   "(input '5', output temp_vers)"}

assign
   token1    = trim(temp_vers)
   temp_vers = "                                                                              ".

if QraConfig:IsEnabled then do:
   c-userid:format = "x(45)".
   c-userid:column = c-userid:column - 10.
   c-password:column = c-password:column - 10.
   lv_domain:column = lv_domain:column - 10.
   c-userid:side-label-handle:column = c-userid:side-label-handle:column - 10.
   c-password:side-label-handle:column = c-password:side-label-handle:column - 10.
   lv_domain:side-label-handle:column = lv_domain:side-label-handle:column - 10.
end.

/*
* CHANGE 'RAW' TO 'CHARACTER' TYPE PARAMETER OF STRING FUNCTIONS
* FOR SUPPORITNG MULTI-BYTE CHARACTERS.
*/
substring(temp_vers,maximum(1,40 -(integer(length(token1,"CHARACTER")/ 2))),-1,"CHARACTER")
   = token1.

repeat while substring(temp_vers,length(temp_vers,"CHARACTER"), 1 , "CHARACTER") = " ":
   temp_vers = substring(temp_vers, 1,length(temp_vers,"CHARACTER") - 1,"CHARACTER").
end.

/*INVOKE THE LICENSING SESSION RECORD LOCK/UNLOCK UTILITY*/
delete procedure lv-handle no-error.
{us/bbi/gprun.i ""lvlock.p"" "persistent set lv-handle"}

/* Get the License Type */
{us/gp/gprunp.i "lvgenpl" "p" "getLicenseType"
   "(input "{&PRODUCT_MFGPRO}",
     input  no,
     output v_licType,
     output v_licDesc)"}

/* Error not trapped on previous call, if MFG/PRO not found, look for EAM */
/* This should never happen                                               */
if v_licDesc = "" then
   {us/gp/gprunp.i "lvgenpl" "p" "getLicenseType"
      "(input "{&PRODUCT_EAM}",
        input  no,
        output v_licType,
        output v_licDesc)"}

/* PRODUCT LICENSE AUDIT */
if v_licType <> {&CONCURRENT-SESSIONS} then
   assign
      v_cur:label in frame welcome = getTermLabel("ACTIVE_USERS",20)
      v_max:label in frame welcome = getTermLabel("DEFINED_USERS",26).

display
   c-welcome
   c-allrightsreserved
   c-notreproduced
   temp_vers
   c-userid
with frame welcome.

/*GET EXPIRATION DAYS, GLOBAL_TIMEOUT_MIN*/
for first usrc_ctrl
no-lock:
   assign
      expdays = usrc_expire_days
      global_timeout_min = usrc_timeout_min
      l_enforce_os_userid = if (usrc__qad02 = "yes") then true else false.
end.

AuthorizeBlock:
do on error undo, leave:

   l_authorized = false.

   if l_enforce_os_userid then do:
      c-userid = global_userid.
      display c-userid with frame welcome.
   end.

   /* GET USER TO LOG IN, TIMEOUT SESSION */
   LoginBlock:
   do while true on endkey undo, leave AuthorizeBlock:

      if password_required then
         update
            c-userid when (not l_enforce_os_userid)
            c-password blank
            with frame welcome
         editing:
            if global_timeout_min > 0
            then do:
               readkey pause global_timeout_min * 60.
               if lastkey = -1 then undo, leave AuthorizeBlock.
            end.
            else
            readkey.
            apply lastkey.
         end.
      
      display
         " " @ c-password
      with frame welcome.

      length(rawPassword) = 0.
      put-string(rawPassword,1) = c-password. 
      
      do on error undo, leave:
         run loginUser
            (input c-userid,
             input rawPassword).
         if return-value = {&SUCCESS-RESULT} or
            return-value = {&WARNING-RESULT} then
            leave LoginBlock.
         
         if QraConfig:IsEnabled then do:
            if return-value = {&INVALID-LICENSE} then do:
               /* CHECK LICENSING */
               {us/bbi/gprun.i ""lvdet.p""
                  "(input  'mf1a.p',
                    output v_secure,
                    output v_sid,
                    output v_cur,
                    output v_max)" }
               
               /* Just quit, since no session was created */
               quit.
               
            end.
            
            else if return-value = {&USER-LIMIT-EXCEEDED} then do:
               /*Concurrent session limit exceeded*/
               {us/bbi/pxmsg.i &MSGNUM=5587 &ERRORLEVEL=4}
               next LoginBlock.
            end.
            
         end.
      end.     /* END DO ON ERROR */

      /* DEAL WITH ERROR RESULT */
      c-status = return-value.

      CASE c-status:
         when ({&INVALID-PASSWORD})   or
         when ({&DISABLED-USERID})    or
         when ({&INVALID-USERID})     then
            i-msg-number = 5546.  /* INVALID USERID/PASSWORD */
         when ({&DEACTIVATED-USERID}) then
	        i-msg-number = 10422.  /* INACTIVE USER */
         when ({&HICHAR-NOT-EXISTING}) then
            i-msg-number = 6278.  /* hi_char.dat does not exist */
         when ({&MISMATCH-COLLATION}) then
            i-msg-number = 7075.  /* Mismatching collations between client and database */
         otherwise
            i-msg-number = 0.
      END CASE.

      if i-msg-number <> 0 and i-msg-number <> 7075 and i-msg-number <> 6278 
      then do:
         run registerReasonMessage
            (input i-msg-number,
             input "",
             input {&INFORMATION-RESULT}).
         pause.
      end.

      CASE c-status:
         when ({&INVALID-USERID}) or
         when ({&INVALID-PASSWORD}) then
         do:
            next LoginBlock.
         end.
         when ({&HICHAR-NOT-EXISTING}) or
         when ({&MISMATCH-COLLATION}) then
         do:
            leave LoginBlock.
         end.
         otherwise
         do on error undo, throw:
            if QraConfig:IsEnabled
            then do on error undo, throw:
               authService:Logout (c-access-token).
               catch e as Progress.Lang.Error:
               end catch.
               finally:
                  quit.
               end finally.
            end.
            else do:
               /* Delete sess_mstr record which is created by AS, also the sesc_det records*/
               {us/px/pxrun.i &PROC='logoutLocal'
                        &PROGRAM='mfaspl.p'
                        &PARAM="(input mfguser,
                        output lChuilogout-response)"}
               quit.
            end.
         end.
      END CASE.

   end.   /* LOGINBLOCK */

   /* Get the application userid which may be different to the login userid */
   {us/px/pxrun.i &PROC='getAppUser'
                  &PROGRAM='mfaspl.p'
                  &PARAM="(input c-userid, output c-userid)"
                  &CATCHERROR=true}

   assign
      global_userid  = c-userid
      passwd         = c-password.

   /* Use Dummy menu program to determine if MFG/PRO or EAM */
   {us/gp/gprunp.i "lvgenpl" "p" "getApplicationOwner"
      "(input  'mf.p',
        input  no,
        output p-application)"}
   
   /* CHECK USER AUTHORIZATION */
   {us/gp/gprunp.i "lvgenpl" "p" "validateUserAuthorization"
       "(input global_userid, 
         input p-application)" }
   
   if return-value = {&USER-NOT-AUTHORIZED}
   then do:
      undo, retry.
   end. /* IF RETURN-VALUE = {&USER-NOT-AUTHORIZED} */

   l_authorized = true.

end.     /* AuthorizeBlock */

if not l_authorized then do on error undo, throw:
   if QraConfig:IsEnabled
   then do on error undo, throw:
      authService:Logout (c-access-token).
      catch e as Progress.Lang.Error:
      end catch.
      finally:
         quit.
      end finally.
   end.
   else do:
      /* Delete sess_mstr record which is created by AS, also the sesc_det records*/
      {us/px/pxrun.i &PROC='logoutLocal'
               &PROGRAM='mfaspl.p'
               &PARAM="(input mfguser,
               output lChuilogout-response)"}
      quit.
   end.
end.

loopdomain:
do on endkey undo,leave:

   assign
      lF4NotPressed = false.

   find udd_det where udd_userid = global_userid no-lock no-error.

   if ambiguous udd_det then do:

      assign
         lMultiDomains = true.

      find first udd_det
       where udd_userid = global_userid
         and udd_primary
      no-lock no-error.

      if available udd_det then lv_domain = udd_domain.

      update lv_domain with frame welcome
      editing:
         if global_timeout_min > 0
         then do:
            readkey pause global_timeout_min * 60.
            if lastkey = -1 then quit.
         end.
         else
         readkey.
         apply lastkey.
      end.
      
      {us/gp/gprunp.i "mgdompl" "p" "ppUserDomDbValidate"
         "(input lv_domain, input global_userid, output l_error)"}

      if l_error > 0 then undo loopdomain, retry.
   end.

   else if available udd_det then do:
      assign
         lMultiDomains = false
         lv_domain = udd_domain.
      display lv_domain with frame welcome.
   end.

   else do on error undo, throw:
      /*DOMAIN IS NOT ASSIGNED TO THE USER*/
      {us/bbi/pxmsg.i &MSGNUM=6170 &ERRORLEVEL=3 &PAUSEAFTER=true}
      if QraConfig:IsEnabled
      then do on error undo, throw:
         authService:Logout (c-access-token).
         catch e as Progress.Lang.Error:
         end catch.
         finally:
            quit.
         end finally.
      end.
      else do:
         /* Delete sess_mstr record which is created by AS, also the sesc_det records*/
         {us/px/pxrun.i &PROC='logoutLocal'
                  &PROGRAM='mfaspl.p'
                  &PARAM="(input mfguser,
                  output lChuilogout-response)"}
         quit.
      end.
   end.

   find dom_mstr where dom_domain = lv_domain no-lock no-error.

   display dom_name with frame welcome.

   /* Check Domain Switch upfront. */
   {us/gp/gprunp.i "mgdompl" "p" " validateDomainSwitch"
      "(input lv_domain, output l_error, output opErrorMsg)"}

   CASE l_error:

      when -5 or when -6 or when 2 or when 3 or when 5 or when 6 then do:
         /* The domain is unavailable or a codepage error happened,  */
         /* block the domain switch.                                 */
         {us/bbi/pxmsg.i &MSGNUM= opErrorMsg &ERRORLEVEL=3 &PAUSEAFTER=TRUE}
         /* This domain will fail, try a new domain. */
         if lMultiDomains then
            undo loopdomain, retry.
         else do on error undo, throw:
            if QraConfig:IsEnabled
            then do on error undo, throw:
               authService:Logout (c-access-token).
               catch e as Progress.Lang.Error:
               end catch.
               finally:
                  quit.
               end finally.
            end.
            else do:
               /* Delete sess_mstr record which is created by AS, also the sesc_det records*/
               {us/px/pxrun.i &PROC='logoutLocal'
                        &PROGRAM='mfaspl.p'
                        &PARAM="(input mfguser,
                        output lChuilogout-response)"}
               quit.
            end.
         end.
      end.

      when 4 then do:
         /* Collation error, show warning message when needed. */
         {us/bbi/pxmsg.i &MSGNUM= opErrorMsg &ERRORLEVEL=2 &PAUSEAFTER=TRUE}
      end.

   END CASE.

   /* Perform domain switch. */
   {us/bbi/gprun.i ""gpmdas.p"" "(input lv_domain, output l_error)"}

   /* Update user's last logon time zone field. */
   for first usr_mstr exclusive-lock where usr_userid = global_userid :
      usr_logon_timezone = global_timezone.
   end.

   assign
      lF4NotPressed = true.

end.

if lF4NotPressed = false then
do:
   if QraConfig:IsEnabled
   then do on error undo, throw:
      authService:Logout (c-access-token).
      catch e as Progress.Lang.Error:
      end catch.
      finally:
         quit.
      end finally.
   end.
   else do:
      /* Delete sess_mstr record which is created by AS, also the sesc_det records*/
      {us/px/pxrun.i &PROC='logoutLocal'
               &PROGRAM='mfaspl.p'
               &PARAM="(input mfguser,
               output lChuilogout-response)"}
      quit.
   end.
end.

if keyfunction(lastkey) = "END-ERROR" then
do:
   if QraConfig:IsEnabled
   then do on error undo, throw:
      authService:Logout (c-access-token).
      catch e as Progress.Lang.Error:
      end catch.
      finally:
         quit.
      end finally.
   end.
   else do:
      /* Delete sess_mstr record which is created by AS, also the sesc_det records*/
      {us/px/pxrun.i &PROC='logoutLocal'
               &PROGRAM='mfaspl.p'
               &PARAM="(input mfguser,
               output lChuilogout-response)"}
      quit.
   end.
end.

if not QraConfig:IsEnabled
then do:
   /* CHECK IF SESSION TIMEOUT FOR THIS USER IN THIS DOMAIN IS SET IN GENERALIZED CODE MAINT.*/
   for first code_mstr
      where code_domain  = global_domain
      and code_fldname = "sess_timeout_min"
      and code_value   = global_userid
   no-lock:
      assign 
         global_timeout_min = integer(code_cmmt) no-error.
   end. /*FOR FIRST code_mstr*/
end.

/* Set the global right header display mode */
find first usrc_ctrl no-lock no-error.
if available usrc_ctrl then global_usrc_right_hdr_disp = usrc_right_hdr_disp.

/*CHECK FOR EURO TOOLKIT RUNNING*/
run checkEurotoolkitLock in h_mfinitpl.

/* SET GLOBAL_USER_NAME, GLOBAL_USER_GROUPS, */
/* GLOBAL_SITE_LIST, GLOBAL_PASSWD           */
run setGlobalUserFields in h_mfinitpl
   (input global_userid,
    input rawPassword).

/* CHECK TO SEE IF DISPLAY LANGUAGE SHOULD CHANGE */
current_user_lang = global_user_lang.

for first usr_mstr where usr_userid = global_userid
no-lock:
   assign
      current_user_lang = usr_lang
      c-countryCode = usr_ctry_code
      c-variantCode = usr_variant_code.
end.

if (current_user_lang <> global_user_lang)
then do:
   {us/mf/mflang.i}
end.

/* Set user specific date and number formats based on user language and
country code*/
for first ctry_mstr where ctry_ctry_code = c-countryCode
no-lock: end.

if available ctry_mstr then
   userISOCountry = ctry_mstr.ctry_code1.
assign
   userISOCountry = if userISOCountry = "" or userISOCountry = ? then
                    'US' else userISOCountry.

{us/gp/gprunp.i "gplocale" "p" "setUserLocale"
   "(input global_user_lang,
     input userISOCountry,
     input c-variantCode)"}.

{us/gp/gpdelp.i "gplocale" "p"}

/* CONNECT TO ALL AVAILABLE DATABASES */
{us/bbi/gprun.i ""mgdcinit.p""}

/*SET USERID FOR ALL CONNECTED DATABASES*/
run setDbUserids in h_mfinitpl
   (input global_userid,
    input rawPassword).

/*SET GLOBAL HIGH-LOW VALUES*/
run setGlobalHighLowValues in h_mfinitpl.

/*SAVE VALUE OF "TERMINAL"*/
if can-find (_field where _field-name = "_frozen") then do:
   {us/bbi/gprun.i ""gpsavtrm.p""}
end.

view frame welcome.

/* Create intrastat control file record */
run createIntrastatControlFile in h_mfinitpl.

/*WARN IF GL_RND_MTHD BLANK*/
for first gl_ctrl where gl_domain = global_domain
                    and gl_rnd_mthd = ''
no-lock:
   /*BASE ROUND METHOD IS BLANK - SETUP IN 36.1*/
   {us/bbi/pxmsg.i &MSGNUM=2247 &ERRORLEVEL=2}
   pause.
end.

/* SET BASE CURRENCY AND ENTITY */
run setBaseCurrencyEntity in h_mfinitpl.

/*SET UP STATUS LINES*/
/* Retrieve the CHUI status lines from msg_mstr */
{us/bbi/pxmsg.i &MSGNUM=8800 &ERRORLEVEL=1 &MSGBUFFER=stline[1]}
{us/bbi/pxmsg.i &MSGNUM=8802 &ERRORLEVEL=1 &MSGBUFFER=stline[2]}
{us/bbi/pxmsg.i &MSGNUM=8814 &ERRORLEVEL=1 &MSGBUFFER=stline[3]}
{us/bbi/pxmsg.i &MSGNUM=8807 &ERRORLEVEL=1 &MSGBUFFER=stline[4]}
{us/bbi/pxmsg.i &MSGNUM=3633 &ERRORLEVEL=1 &MSGBUFFER=stline[5]}
{us/bbi/pxmsg.i &MSGNUM=8815 &ERRORLEVEL=1 &MSGBUFFER=stline[6]}
{us/bbi/pxmsg.i &MSGNUM=8816 &ERRORLEVEL=1 &MSGBUFFER=stline[7]}
{us/bbi/pxmsg.i &MSGNUM=8817 &ERRORLEVEL=1 &MSGBUFFER=stline[8]}
{us/bbi/pxmsg.i &MSGNUM=8818 &ERRORLEVEL=1 &MSGBUFFER=stline[9]}
{us/bbi/pxmsg.i &MSGNUM=8819 &ERRORLEVEL=1 &MSGBUFFER=stline[10]}
{us/bbi/pxmsg.i &MSGNUM=3632 &ERRORLEVEL=1 &MSGBUFFER=stline[11]}
{us/bbi/pxmsg.i &MSGNUM=8820 &ERRORLEVEL=1 &MSGBUFFER=stline[12]}
{us/bbi/pxmsg.i &MSGNUM=8821 &ERRORLEVEL=1 &MSGBUFFER=stline[13]}

/* SET UP HELPKEY DEFINITIONS */

/* MFG/PRO STANDARD DEFINITIONS:                                   */
/* F1 - Go             F5 - Delete          F9  - Previous         */
/* F2 - Help           F6 - User Menu       F10 - Next             */
/* F3 - Insert         F7 - Recall          F11 - Cut&Paste Buffer */
/* F4 - End-Error      F8 - Clear           F12 - Cut&Paste        */
/* Scrolling Windows:  F7/8 - Page-Up/Down  F9/10 - Line-Up/Down   */

/* Function/Control Key Defines for Character Mode */
/* DISPLAYS FIELD NAME */
on CTRL-F help.
on ESC-TAB help.

/* INSERT-REPLACE MODE */
on F3 insert-mode.          /* Override Progress version 7 default */
on PF3 insert-mode.

/* USER MENU */
on CTRL-P help.
on F6 help.

/* STORE/GET FIELD VALUE */
on CTRL-B help.
on F11 help.

on CTRL-A help.
on F12 help.

/* FIND THE HIGHEST FUNCTION KEY USED TO SET HELP KEYS */
define variable max_fkey as integer initial 12 no-undo.

do for ufd_det transaction:

   for last ufd_det where ufd_userid = global_userid 
   no-lock:
      if ufd_fkey > max_fkey then
         assign max_fkey = ufd_fkey.
   end.

   for last ufd_det where ufd_userid = "" 
   no-lock:
      if ufd_fkey > max_fkey then
         assign max_fkey = ufd_fkey.
   end.

end.

if max_fkey >= 13 then on f13 help.
if max_fkey >= 14 then on f14 help.
if max_fkey >= 15 then on f15 help.
if max_fkey >= 16 then on f16 help.
if max_fkey >= 17 then on f17 help.
if max_fkey >= 18 then on f18 help.
if max_fkey >= 19 then on f19 help.
if max_fkey >= 20 then on f20 help.
if max_fkey >= 21 then on f21 help.
if max_fkey >= 22 then on f22 help.
if max_fkey >= 23 then on f23 help.
if max_fkey >= 24 then on f24 help.
if max_fkey >= 25 then on f25 help.
if max_fkey >= 26 then on f26 help.
if max_fkey >= 27 then on f27 help.
if max_fkey >= 28 then on f28 help.
if max_fkey >= 29 then on f29 help.
if max_fkey >= 30 then on f30 help.
if max_fkey >= 31 then on f31 help.
if max_fkey >= 32 then on f32 help.
if max_fkey >= 33 then on f33 help.
if max_fkey >= 34 then on f34 help.
if max_fkey >= 35 then on f35 help.
if max_fkey >= 36 then on f36 help.
if max_fkey >= 37 then on f37 help.
if max_fkey >= 38 then on f38 help.
if max_fkey >= 39 then on f39 help.

if not QraConfig:IsEnabled
then do:
   /* Populate mfguser by AS if mfguser is blank */
   if mfguser = ""
   then do:
      /* Use session manager to create session id */
      {us/px/pxrun.i &PROC='createSession'
               &PROGRAM='mfsemstr.p'
               &PARAM="(input global_userid,
                        output mfguser)"}
   end.
end.

/* We should still have a share lock on qad_wkfl but no transaction */
{us/bbi/gprun.i ""gpistran.p"" "(input 1, input ' ')"}

/* Set global-do-menu-substitution */
run setGlobalMenuSubstitution in h_mfinitpl
   (input global_userid).

/* Set global variable if global requisition system installed */
run setUsingGRS in h_mfinitpl.

unsubscribe to "previousSuccessfulLogin" in h_mfinitpl.

/* Delete the initialization procedure library*/
if valid-handle(h_mfinitpl)
   and h_mfinitpl:type = "PROCEDURE"
   and h_mfinitpl:file-name = "mfinitpl.p" 
then
   delete procedure h_mfinitpl.

/*MENU PROCESSING FOR CHARACTER*/
pause 0.

/* CHECK LICENSING */
{us/bbi/gprun.i ""lvdet.p""
   "(input  'mf1a.p',
     output v_secure,
     output v_sid,
     output v_cur,
     output v_max)" }

display
   v_cur
   v_max
with frame welcome.

/* TRAP ERROR & ENDKEY TO CONTINUE WITH LOGIN */
do on error undo, leave on endkey undo, leave:
   /* DISPLAY A MESSAGE SHOWING LAST SUCCESSFUL LOGON DATE */
   /* AND TIME. LAST SUCCESSFULL LOGIN: # # #              */
   {us/bbi/pxmsg.i &MSGNUM=6085
            &MSGARG1=c-last-log-date
            &MSGARG2=c-last-log-time
            &MSGARG3=c-last-log-zone
            &PAUSEAFTER=5}
end.

if not v_secure then quit.

/* Share-lock the cnt_mstr records */
run lv_cnt_lock in lv-handle
   (input v_sid,
    input p-application).

/* Exclusive-lock the mon_mstr records */
run lv_mon_lock in lv-handle
   (input  mfguser,
    input  p-application,
    output l_locked).

/* AIM API STARTUP PROCESSING */
{us/bbi/gprun.i ""whapist.p""}

/* API STARTUP PROCESSING */
{us/bbi/gprun.i ""gpapist.p""}

/* CALCULATE AND SET HIGH WATER MARK LEVEL FOR ALL REGISTERED PRODUCTS */
/* FOR EACH LOGIN OF PRODUCT  FOR THE DAY*/
hwm:
do on error undo , leave :

   {us/gp/gprunp.i "lvgenpl" "p" "setHighWaterMark"
      "(input p-application)"  }

   if return-value = {&RECORD-NOT-FOUND}
   then do:
      /* APPLICATION # NOT REGISTERED */
      {us/bbi/pxmsg.i &MSGNUM=2476 &ERRORLEVEL=2 &MSGARG1=p-application }

   end. /* IF return-value = {&RECORD-NOT-FOUND} */

end. /* DO ON ERROR */

/* RECORD LICENSE USAGE RECORDS (lua_det) FOR EACH  */
/* SESSION WITHIN AUDIT PERIOD */
{us/gp/gprunp.i "lvgenpl" "p" "createLicenseUsageRecord"
   "(input global_userid,
     input mfguser,
     input p-application,
     input yes)"}

/* Check to see if Primary Entity has been defined */
if current_entity = "" then do:

   /* Check the Financials Tables to see if an entity is defined */
   assign
      icUsrLogin = global_userid.

   /* Find the Valid Domains and Entities for this User */
   {proxy/session/getdomainsandcompaniesforuserrun.i}

   /* Error handling */
   if oiReturnStatus < 0 then do:
      /* Start qflib.p - QAD Financials Library running persistently */
      run mfairunh.p
         (input 'qflib.p',
          input '?',
          output hQADFinancialsLib) no-error.
      run processErrors in hQADFinancialsLib
         (input table tFcMessages,
          input 3).

      do:
         if QraConfig:IsEnabled
         then do on error undo, throw:
            authService:Logout (c-access-token).
            catch e as Progress.Lang.Error:
            end catch.
            finally:
               quit.
            end finally.
         end.
         else quit.
      end.
   end.

   find first tDomainsCompanies where tcDomainCode = global_domain
      and tlIsPrimaryCompany
   no-lock no-error.

   if available tDomainsCompanies then do:
      current_entity = tcCompanyCode.
   end.

   /* If cannot find primary entity, try for any entity for this user */
   else do:

      find first tDomainsCompanies where tcDomainCode = global_domain
      no-lock no-error.

      if available tDomainsCompanies then
         current_entity = tcCompanyCode.

   end.

   if current_entity = "" then do:
      hide message no-pause.
      /* Primary entity not defined for Domain: # */
      {us/bbi/pxmsg.i &MSGNUM=1701 &ERRORLEVEL=4 &MSGARG1=global_domain}
      pause.

      do:
         if QraConfig:IsEnabled
         then do on error undo, throw:
            authService:Logout (c-access-token).
            catch e as Progress.Lang.Error:
            end catch.
            finally:
               quit.
            end finally.
         end.
         else quit.
      end.
   end.

end.

/* Check to see if User is authorized for Primary Entity */
{us/gl/glenchk.i &entity=current_entity &entity_ok=valid_entity}

if not valid_entity then do:
   hide message no-pause.
   /* User not authorized for primary entity in Domain # */
   {us/bbi/pxmsg.i &MSGNUM=1590 &ERRORLEVEL=4 &MSGARG1=global_domain}
   pause.
   do:
      if QraConfig:IsEnabled
      then do on error undo, throw:
         authService:Logout (c-access-token).
         catch e as Progress.Lang.Error:
         end catch.
         finally:
            quit.
         end finally.
      end.
      else quit.
   end.
end.

/* RUN THE MENU DRIVER */
l_suddenExit = true.
mfmenu_blk:
do on stop undo, leave mfmenu_blk:
   {us/bbi/gprun1.i ""mfmenu.p"" "(input p-application)"}
   l_suddenExit = false.
end.

/* Set the execname to "mfmenu.p" so that UCA can catch the 'sys-out' event   */
/* for the following scenarios:                                               */
/*    1. The user quits MFG/Pro immediately after she/he entered an invalid   */
/*       program/choice;                                                      */
/*    2. The user quits MFG/Pro immediately after she/he tried to run a .NetUI*/
/*       program from CHUI client;                                            */
/*    3. Other cases that cause execname not equal to either "" or "mfmenu.p" */
execname = "mfmenu.p".

/* CLEAN UP THE QAD_WKFL RECORDS FOR THE CTRL-B FEATURE */
for each qadwkfl where qadwkfl.qad_domain = global_domain and
                       qadwkfl.qad_key1 = mfguser
exclusive-lock:
   delete qadwkfl.
end.

{us/px/pxrun.i &PROC='logoffFinancials'
               &PROGRAM='mfinitpl.p'
               &HANDLE=h_mfinitpl
               &CATCHERROR=True}

/* DELETE LICENSING SESSION/MONITOR RECORDS */
run lv_delete in lv-handle.

/* API SHUTDOWN PROCESSING */
{us/bbi/gprun.i ""gpapish.p""}
/* AIM API SHUTDOWN PROCESSING */
{us/bbi/gprun.i ""whapish.p""}

if QraConfig:IsEnabled
then do on error undo, throw:
   authService:Logout (c-access-token).
   catch e as Progress.Lang.Error:
   end catch.
end.
else do:
   /* Delete sess_mstr record which is created by AS, also the sesc_det records*/
   {us/px/pxrun.i &PROC='logoutLocal'
            &PROGRAM='mfaspl.p'
            &PARAM="(input mfguser,
                     output lChuilogout-response)"}
end.

/* Don't quit MFG/Pro if the user pressed CTRL-C or any equivalent keys to */
/* stop the session.                                                       */
if l_suddenExit then do:
   mfguser = "".
   stop.
end.
else
   quit.

PROCEDURE getNewPassword:
/*------------------------------------------------------------------
  Purpose:    Get new password from user
  Exceptions:
  Notes:
------------------------------------------------------------------*/
   define input parameter           p-userid       as character no-undo.
   define input parameter           p-passwd       as raw no-undo.
   define input parameter           p-status-code  as character no-undo.
   define output parameter          p-newpasswd    as raw no-undo.

   /* DEFINE HANDLES FOR THE PROGRAMS. */
   {us/px/pxphdef.i lib}
   {us/px/pxphdef.i setpassword}

   define variable i-msg-number      as integer no-undo.
   define buffer usr_mstr            for usr_mstr.

   define variable c-passwd as character no-undo.
   
   if length(p-passwd) > 0 then
      c-passwd = get-string(p-passwd,1,length(p-passwd, "RAW")).
   
   case p-status-code:
      when ({&EXPIRED-PASSWORD}) then
         /* PASSWORD HAS EXPIRED */
         i-msg-number = 5564.
      when ({&FORCE-PASSWD-CHANGE}) then
         /* CHANGE YOUR PASSWORD IMMEDIATELY */
         i-msg-number = 6082.
      otherwise
         i-msg-number = 0.
   end case.

   if i-msg-number <> 0 
   then do:
      run registerReasonMessage
         (input i-msg-number,
          input "",
          input {&INFORMATION-RESULT}).
      pause.
   end.

   /* NEED TO ASSIGN global_userid HERE BASED ON WHAT USER HAS ENTERED.  */
   assign
      global_userid = p-userid.

   for first usr_mstr where usr_userid = p-userid
   no-lock: end.

   do on error undo, return error return-value:
      /* BE PREPARED TO FIELD AN APP-ERROR-RETURN */
      {us/px/pxrun.i &PROC='promptNewPasswordAndReturn'
               &PROGRAM='mgurlib.p'
               &HANDLE=ph_setpassword
               &PARAM="(input p-userid,
                        input encode(c-passwd),
                        output p-newpasswd)"
               &NOAPPERROR=True
               &CATCHERROR=True}
      c-status = return-value.
      delete procedure ph_setpassword no-error.
   end.
   if c-status = {&SUCCESS-RESULT} then
      return {&SUCCESS-RESULT}.
   else
      return error {&APP-ERROR-RESULT}.

END PROCEDURE.

PROCEDURE loginUser:
/*------------------------------------------------------------------
 Purpose:    Authenticate user and get new password when necessary.
 Exceptions: Errors returned when raised in call to checkLogon:
             &INVALID-USERID
             &INVALID-PASSWORD
             &DEACTIVATED-USERID
             &HICHAR-NOT-EXISTING
 Notes:
------------------------------------------------------------------*/
   define input parameter p-userid     as character no-undo.
   define input parameter p-password   as raw no-undo.

   define variable newPassword as raw no-undo.
   define variable c-status as character no-undo.
   define variable c-userid as character no-undo.
   
   c-logon = {&CHECKLOGON-LOGON}.     /* CALLED FROM LOGON PROGRAM */

   do on error undo, return error return-value:

      if QraConfig:IsEnabled
      then do:
         {us/px/pxrun.i &PROC='checkLogonQra'
                   &PROGRAM='mfinitpl.p'
                   &HANDLE=h_mfinitpl
                   &PARAM="(input p-userid, input p-password, input c-logon, output c-access-token)"
                   &CATCHERROR=True}
      end.
      else do:
         {us/px/pxrun.i &PROC='checkLogon'
                  &PROGRAM='mfinitpl.p'
                  &HANDLE=h_mfinitpl
                  &PARAM="(input p-userid, input p-password, input c-logon)"
                  &CATCHERROR=True}
      end.
      
      c-status = return-value.
      
      /* Get the application userid if the passed in userid is email/active dir */
      {us/px/pxrun.i &PROC='getAppUser'
                     &PROGRAM='mfaspl.p'
                     &PARAM="(input p-userid, output c-userid)"
                     &CATCHERROR=true}
      
      case c-status:
         when ({&EXPIRED-PASSWORD}) or
         when ({&FORCE-PASSWD-CHANGE}) then
         do on error undo, return error return-value:
            run getNewPassword(input c-userid,
                               input p-password,
                               input c-status,
                               output newPassword).
            c-status = return-value.
            if QraConfig:IsEnabled
            then do on error undo, throw:
               
               {us/px/pxrun.i &PROC='checkLogonQra'
                   &PROGRAM='mfinitpl.p'
                   &HANDLE=h_mfinitpl
                   &PARAM="(input c-userid, input newPassword, input c-logon, output c-access-token)"
                   &CATCHERROR=True}
               
               c-status = return-value.
               c-application-mode = "".
            end.
         end.
         when ({&WARNING-RESULT}) then
         do:
            c-ret-message = offerNewPassword(input c-userid).
            if c-ret-message <> "" then
            do on error undo, leave:
               /* Do you wish to change password? */
               {us/bbi/pxmsg.i &MSGNUM=6088
                        &MSGARG1=c-ret-message
                        &CONFIRM=l-ret-value}

               if l-ret-value then
                  run getNewPassword
                     (input c-userid,
                      input p-password,
                      input "",
                      output newPassword).
               /* WE DON'T CARE ABOUT ERROR RETURNS FROM HERE */
            end.
            c-status = {&SUCCESS-RESULT}.
         end.
      end case.

      return c-status.
   
   end.    /* END DO ON ERROR */

END PROCEDURE.  /* loginUser */

PROCEDURE previousSuccessfulLogin:
/*------------------------------------------------------------------
  Purpose:    Format data for last successful Login
  Exceptions:
  Notes:
------------------------------------------------------------------*/
   define input parameter p-logon-date as character no-undo.
   define input parameter p-logon-time as integer   no-undo.
   define input parameter p-logon-zone as character no-undo.

   assign
      c-last-log-date = p-logon-date
      c-last-log-time = string(p-logon-time, "HH:MM:SS")
      c-last-log-zone = p-logon-zone.

END PROCEDURE.

FUNCTION offerNewPassword returns character
   (input p-userid as character):
/*------------------------------------------------------------------
 Purpose:    Puts up dialog box for asking a question
 Exceptions:
 Notes:
------------------------------------------------------------------*/
   define variable l-ret-value like mfc_logical no-undo.
   define variable i-days-left as integer       no-undo.
   define buffer   usr_mstr  for usr_mstr.

   define variable c-question  as character no-undo .
   define variable c-expire    as character no-undo .
   define variable c-text      as character no-undo .

   /* GET NUMBER OF DAYS LEFT BEFORE PASSWORD EXPIRES */
   for first usr_mstr
      where usr_mstr.usr_userid = p-userid no-lock:
      i-days-left = dynamic-function('passwordDaysLeft' in h_mfinitpl,
                                   buffer usr_mstr).
   end.

   /* FIX IF DAYS ARE A NEGATIVE VALUE */
   if i-days-left < 0 then
      i-days-left = i-days-left * -1.

   /* PASSWORD WILL EXPIRE IN DAYS: # */
   {us/bbi/pxmsg.i &MSGNUM=6083
            &MSGBUFFER=c-expire
            &MSGARG1=i-days-left}
   return c-expire.

END FUNCTION.

PROCEDURE registerReasonMessage:
/*------------------------------------------------------------------
 Purpose: Message handler for mfinitpl.p and other procedures
 Exceptions:
 Notes:
 ------------------------------------------------------------------*/
   define input parameter pMessageNumber as integer no-undo.
   define input parameter pMessageDescription as character no-undo.
   define input parameter pMessageSeverity as integer no-undo.

   define variable severity as integer no-undo.

   severity = pMessageSeverity.
   
   if severity = 3 then
      severity = 4. /*DON'T WANT "PLEASE RE-ENTER"*/

   if pMessageDescription > '' then do:
      {us/bbi/pxmsg.i &MSGTEXT=pMessageDescription &ERRORLEVEL=severity}
   end.
   else do:
      {us/bbi/pxmsg.i &MSGNUM=pMessageNumber &ERRORLEVEL=severity}
   end.

END PROCEDURE.
